<?php
if(!defined('BARCODE_PATH')){
    define('BARCODE_PATH', __DIR__.'/');
}
require_once(BARCODE_PATH.'class/BCGFontFile.php');
require_once(BARCODE_PATH.'class/BCGColor.php');
require_once(BARCODE_PATH.'class/BCGDrawing.php');

// Including the barcode technology


// Loading Font

class CreateBarcode{

    private $_tmpPath = '/tmp/';
    function __construct($code,$tmpPath = false)
    {
        if(!empty($tmpPath))  $this->_tmpPath = $tmpPath;
        $this->_code = $code;
        require_once(BARCODE_PATH."class/$code.barcode.php");
    }

    private  function _getTmpPath(){
        return $this->_tmpPath;
    }

    function run($text,$fname,$fileType='PNG',$arg){
        $code = $this->_code;
        $font = new BCGFontFile(BARCODE_PATH.'/font/Arial.ttf', 8);

        $text = isset($text) ?$text : 'HELLO';
		if($arg["idWith0"]){
			$text = "0".$text;
		}
		$scale = isset($arg["scale"]) ? $arg["scale"] : 1;
		$thickness = isset($arg["thickness"]) ? $arg["thickness"] : 25;
		$font = isset($arg["fontdisplay"])&&$arg["fontdisplay"]!=0 ? 0 : $font;

        $color_black = new BCGColor(0, 0, 0);
        $color_white = new BCGColor(255, 255, 255);

        $drawException = null;
        try {
            $code = new $code();
            $code->setScale($scale); // Resolution
            $code->setThickness($thickness); // Thickness
            $code->setForegroundColor($color_black); // Color of bars
            $code->setBackgroundColor($color_white); // Color of spaces
            $code->setFont($font); // Font (or 0)
            $code->parse($text); // Text
        } catch(Exception $exception) {
            $drawException = $exception;
        }

        /* Here is the list of the arguments
        1 - Filename (empty : display on screen)
        2 - Background color */
        $drawing = new BCGDrawing($fname, $color_white);
        if($drawException) {
            $drawing->drawException($drawException);
        } else {
            $drawing->setBarcode($code);
            $drawing->draw();
            $filetypes = array('PNG' => BCGDrawing::IMG_FORMAT_PNG, 'JPEG' => BCGDrawing::IMG_FORMAT_JPEG, 'GIF' => BCGDrawing::IMG_FORMAT_GIF);
            $drawing->finish($filetypes[$fileType]);
        }
    }

	//生成的图片类型固定为png格式
    function getImgData($text,$arg = array()){
        $fname = $this->_getTmpPath().uniqid().'.png';
        $this->run($text,$fname,"PNG",$arg);
        $r = file_get_contents($fname);
        unlink($fname);//删除临时文件
        return base64_encode($r);
    }
}